package com.oi.test01.hw.tiMu8;

import com.oi.test01.entity.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * @author bin
 * @date 2025 - 03 -19
 * 八、使用反射，创建一个学生类型的数组，存放二个学生，循环遍历输出，要求如下：
 *     1、第一个学生要求使用默认构造方法实例化并使用用 set 方法初始化对象
 *     2、第二个学生要求使用下面的构造方法实例化对象
 *         Student(String name,int age,Double score)
 **/
public class MainTest01 {
    public static void main(String[] args) throws Exception{
        Student[] students = new Student[2];

        //创建第一个学生并添加
        Class<Student> studentClass = Student.class;
        Constructor<Student> constructor = studentClass.getConstructor();
        Object obj = constructor.newInstance();

        Method setName = studentClass.getDeclaredMethod("setName", String.class);
        Method setAge = studentClass.getDeclaredMethod("setAge", int.class);
        Method setWeight = studentClass.getDeclaredMethod("setWeight", float.class);
        setName.invoke(obj,"张三");
        setAge.invoke(obj,20);
        setWeight.invoke(obj,55.5f);
        students[0] = (Student) obj;

        //创建第二个学生 并添加
        Constructor<Student> constructor1 = studentClass.getConstructor(String.class, int.class, float.class);
        Object obj1 = constructor1.newInstance("李四", 21, 66.5f);
        students[1] = (Student) obj1;

        //遍历输出
        for (Student student : students) {
            System.out.println(student);
        }

    }
}
